//
//  MainViewController.swift
//  MAGweibo
//
//  Created by MagicaL on 15/7/28.
//  Copyright © 2015年 MagicaL. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        
        addAllChildViewControllers()
        
    }
    // 在viewDidAppear中 添加撰写按钮
    override func viewDidAppear(animated: Bool) { // 不能忘记调用 super.viewDidAppear
        
        super.viewDidAppear(animated)
        setupComposeBtn()
    }
    
    /// 设置撰写按钮
    private func setupComposeBtn() { // 不能忘函数名后面的参数列表"()"    compose撰写 由....组成 创作
        
        let w = tabBar.bounds.width / CGFloat(viewControllers!.count)
        
        composeBtn.frame = CGRectMake(2 * w, 0, w, tabBar.bounds.height)
    
    }
    
    
    /// 添加所有的子控制器
    private func addAllChildViewControllers() {
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())  // 这个函数并不是自定义的
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")

        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")

    }
    
    // swift 支持函数重载 也就是函数名可以相同 参数个数不同
    /// 自定义添加自控制器方法 原方法仅一个参数
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        
//        tabBar.tintColor = UIColor.orangeColor()
//        let vc = HomeTableViewController()
        vc.title = title
        let nav = UINavigationController(rootViewController: vc)
        
        vc.tabBarItem.image = UIImage(named:imageName)
        
        addChildViewController(nav)
    }
    
    ///懒加载 composeBtn
    lazy private var composeBtn:UIButton = {
    
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
       
        // 将按钮添加到 tabbar中   同时注意闭包中需要用self. 来引用  且没有智能提示
        self.tabBar.addSubview(btn)
        
        // 增加按钮点击事件
        btn.addTarget(self, action: "clickComposeBtn", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn

    }()
    
    /// 运行循环监听到事件后, 向VC发送消息,动态执行方法,因此不能设置为 private
    func clickComposeBtn() {
    
        print(__FUNCTION__)
    
    }

}
